﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PSWebLogic;
using System.Web.UI.MobileControls;
using IPSWeb.Logic;
using System.Configuration;
using System.IO;


namespace IPSWeb
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
         
      
            if (Session["psrunspace"] == null)
            {

                Session["psrunspace"] = PSUtil.GetNewRunspaceObject(PSConfigurationManager.GetPSSnapInsToAdd(), PSConfigurationManager.GetPSSnapInsToRemove());
                PSUtil.ExecuteComand(new List<PSCommand>() { new PSCommand() { CommandText = string.Format("cd {0}", PSConfigurationManager.GetScriptDirectoryPath()) } }, Session["psrunspace"]);
                if (File.Exists(PSConfigurationManager.GetStartupScriptPath()))
                {

                    PSUtil.ExecuteScript(PSConfigurationManager.GetStartupScriptPath(), Session["psrunspace"]);
                }
                tbShell.Text += "*************************************************";
                tbShell.Text += "\n Welcome To IPSWeb. \n you can execute from here any powershell command or script you want, over the web. \n Attention: This application is in development. do not use on production servers!";
                tbShell.Text += "\n The current location is your script directory, as you entered in the configuration file: " + PSConfigurationManager.GetScriptDirectoryPath();
                tbShell.Text += "\n *************************************************";
                upShell.Update();
            }
            if (!string.IsNullOrEmpty(Request["ScriptPath"]))
            {
                tbShell.Text += "\n PowerShell Over WEB: Executing Script ==> " + HttpUtility.UrlDecode(Request["ScriptPath"].ToString()) + " \n";
                tbShell.Text += PSUtil.ExecuteScript(Request["ScriptPath"].ToString(), Session["psrunspace"]);
            }
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            tbShell.Text += string.Format("\n PowerShell Over WEB ==> {0} \n", tbCommand.Text);
            tbShell.Text += PSUtil.ExecuteComand(new List<PSCommand>() { new PSCommand() { CommandText = tbCommand.Text } }, Session["psrunspace"]);
            ScriptManager.RegisterClientScriptBlock(tbShell,Page.GetType(),"scroll",string.Format("document.getElementById('{0}').scrollTop = document.getElementById('{1}').scrollHeight;",tbShell.ClientID,tbShell.ClientID),true);
            tbCommand.Text = "";
            tbCommand.Focus();
        }
    }
}
